﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileManagerLibrary.Base;
using System.Windows.Forms;
using System.IO;
using FileManagerBase;
using FileManagerLibrary.Base.FileBase;
using FileManagerLibrary.Base.UIData;
using Logging;

namespace FileManagerTool
{
    public class FolderManagerController: BackupJobManagerControllerBase
    {
        public FolderManagerController(BackupJobManagerView view, BackupJob currentJob, bool isEditMode)
            :base(view,currentJob, isEditMode)
        {
            View.cmbMonth.SelectedIndex = 0;
            View.cmbWeek.SelectedIndex = 0;
            View.cmbCleanup.SelectedIndex = 0;
        }

        internal void HndlBrowseFolder()
        {
            if (View.lstExcludedFolders.Items.Count > 0)
            {
                MessageBox.Show("Cannot change Root Path. Remove the exclutions first.");
                return;
            }
            string path = FileOperations.Getfolder();
            if (path == "")
                return;
            View.txtRootFolder.Text = path;
            if (View.txtBackupSetName.Text.Length == 0)
                View.txtBackupSetName.Text = path;
        }

        internal void HndlCopyFromClipBoard()
        {
            if (View.lstExcludedFolders.Items.Count > 0)
            {
                MessageBox.Show("Cannot change Root Path. Remove the exclutions first.");
                return;
            }
            string tmp = GetDirectoryFromClipBoard();
            if (tmp != "")
            {
                View.txtRootFolder.Text = tmp;
                //setting the path name of the Jobname as same as path if it is empty for now.
                if (View.txtBackupSetName.Text.Length == 0)
                    View.txtBackupSetName.Text = View.txtRootFolder.Text;
            }
        }
        
        internal int validated;
        internal void HndlCopyModeCheckChanged(object sender)
        {
            //View.LoadMode = true;
            if (validated > 0)
            {
                validated--;
                return;
            }
            if (View.IsUILoading == false)
            {
                if (View.rdoMove.Checked == true || View.rdoDelete.Checked == true)
                {
                    if (MessageBox.Show("This will delete the files from the source location. Continue?", "Delete Files", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        validated = 2; // to cancel one uncheck and one check
                        ((RadioButton)sender).Checked = true;
                        validated++; // to cancel the above check
                    }
                    else
                    {
                        validated++;
                    }
                }
            }
            if (View.rdoCopy.Checked == true || View.rdoMove.Checked == true)
            {
                View.lblbcklocation.Visible = true;
                View.txtbckLocation.Visible = true;
                View.btnbckLocation.Visible = true;
                View.btnCopyCliptoDestination.Visible = true;
            }
            else
            {
                View.lblbcklocation.Visible = false;
                View.txtbckLocation.Visible = false;
                View.btnbckLocation.Visible = false;
                View.btnCopyCliptoDestination.Visible = false;
            }
            if (View.rdoCopy.Checked == true)
            {
                //View.chkDeleteEmptyFolders.Visible = false;
                View.chkDeleteEmptyFolders.Text = "Include Empty Folders";
                View.chkDeleteEmptyFolders.Checked = CurrentJob.FolderSettings.IncludeEmptyFolders;
            }
            else
            {
                View.chkDeleteEmptyFolders.Text = "Delete Empty Folders from Source";
                if (View.rdoMove.Checked == true)
                {
                    View.IsUILoading = true;
                    View.chkDeleteEmptyFolders.Checked = true;
                    View.IsUILoading = false;
                }
                else
                    View.chkDeleteEmptyFolders.Checked = CurrentJob.FolderSettings.IncludeEmptyFolders;
            }
            if (View.rdoCopy.Checked == true)
                View.groupBox12.Visible = true;
            else
                View.groupBox12.Visible = false;

            //View.LoadMode = false;
        }

        internal void HandleOnFolderScheduleModeChanged()
        {
            if (View.rdoMonth.Checked == true)
            {
                View.cmbWeek.Visible = false;
                View.cmbWeek.Enabled = false;
                View.cmbMonth.Visible = true;
                View.cmbMonth.Enabled = true;
            }
            else if (View.rdoWeek.Checked == true)
            {
                View.cmbWeek.Visible = true;
                View.cmbWeek.Enabled = true;
                View.cmbMonth.Visible = false;
                View.cmbMonth.Enabled = false;
            }
            else if (View.RdoDay.Checked == true)
            {
                View.cmbWeek.Visible = false;
                View.cmbWeek.Enabled = false;
                View.cmbMonth.Visible = true;
                View.cmbMonth.Enabled = false;
            }
        }

        internal void HndlDeleteEmptyFoldersCheckChanged()
        {
            if (View.IsUILoading == false)
            {
                if (View.chkDeleteEmptyFolders.Checked == true && View.rdoCopy.Checked == false)
                    if (MessageBox.Show("This will delete the complete tree of subfolders from directory if it is empty. Do you want to do that?", "Delete SubFolders", MessageBoxButtons.YesNo) == DialogResult.No)
                        View.chkDeleteEmptyFolders.Checked = false;
            }
        }

        internal void HndlCopyfrmClipBoard()
        {
            if (ValidateContents(LevelsEnum.Level1) == false)
                return;
            FileSystemCollection flcol = GetFileSystemListFromClipBoard();
            if (flcol.Files.Count == 0 && flcol.Folders.Count == 0)
                return;
            foreach (var path in flcol.Folders)
            {
                if (View.txtRootFolder.Text == path)
                {
                    Logger.StaticLogger.AddErrorLogEntry("Error in path: " + path + ". You cannot select Root Folder as Sub Folder.");
                    return;
                }
                if (FileOperations.IsSubfolder(View.txtRootFolder.Text, path) == false)
                {
                    Logger.StaticLogger.AddErrorLogEntry("Error in path: " + path + ". You selected a folder outside Root Folder: " + View.txtRootFolder.Text + ".");
                    return;
                }
                View.lstExcludedFolders.Items.Add(path);
            }
            foreach (var fldr in flcol.Files)
            {
                if (FileOperations.IsSubfolder(View.txtRootFolder.Text, fldr) == false)
                {
                    Logger.StaticLogger.AddErrorLogEntry("Error in file: " + fldr + ". You selected a file outside Root Folder: " + View.txtRootFolder.Text + ".");
                    return;
                }
                View.lstExcludedFolders.Items.Add(fldr);
            }
        }

        internal void HndlAddFile()
        {
            if (ValidateContents(LevelsEnum.Level1) == false)
                return;
            string[] path = FileOperations.GetFiles(View.txtRootFolder.Text);
            if (path == null)
                return;
            if (path.Length == 0)
                return;
            if (FileOperations.IsSubfolder(View.txtRootFolder.Text, path[0]) == false)
            {
                MessageBox.Show("You selected a file outside Root Folder: " + View.txtRootFolder.Text + ".", "Wrong path", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            View.lstExcludedFolders.Items.AddRange(path);
        }

        public override bool ValidateContents(LevelsEnum level)
        {
            if (level == LevelsEnum.Level2)
                return true;
            if (View.txtBackupSetName.Text.Length == 0)
            {
                MessageBox.Show("Enter a Job Name.");
                return false;
            }
            if (View.txtRootFolder.Text.Length == 0)
            {
                MessageBox.Show("Root folder Not Specified");
                return false;
            }
            if (Directory.Exists(View.txtRootFolder.Text) == false)
            {
                DialogResult rst = MessageBox.Show("Cannot find Root Source Folder. Create One?", "Folder Missing", MessageBoxButtons.YesNoCancel);
                if (rst == DialogResult.Yes)
                    Directory.CreateDirectory(CurrentJob.RootSourceFolder);
                else if (rst == DialogResult.Cancel)
                {
                    return false;
                }
                //else continue without folder.
            }
            if(level == LevelsEnum.Level1)
                return true;
            if (View.rdoCopy.Checked == true || View.rdoMove.Checked == true)
            {
                if (View.txtbckLocation.Text == "")
                {
                    MessageBox.Show("Destination folder required. Cannot proceed.");
                    return false;
                }
            }
            return true;
        }

        internal void HndlAddFolder()
        {
            if (ValidateContents(LevelsEnum.Level1) == false)
                return;
            string path = FileOperations.Getfolder(View.txtRootFolder.Text);
            if (path == null || path.Length == 0)
                return;
            if (View.txtRootFolder.Text == path)
            {
                MessageBox.Show("You cannot select Root Folder as Sub Folder.", "Wrong path", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (FileOperations.IsSubfolder(View.txtRootFolder.Text, path) == false)
            {
                MessageBox.Show("You selected a folder outside Root Folder: " + View.txtRootFolder.Text + ".", "Wrong path", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            View.lstExcludedFolders.Items.Add(path);
        }

        public override void ReloadData()
        {
            View.IsUILoading = true;
            View.txtRootFolder.Text = CurrentJob.RootSourceFolder;
            View.txtBackupSetName.Text = CurrentJob.JobSetName;
            View.chkIncludeSubFolders.Checked = CurrentJob.FolderSettings.IncludeSubfolders;
            foreach (var item in CurrentJob.FolderSettings.ExcludedLocations)
            {
                View.lstExcludedFolders.Items.Add(item);
            }
            View.cmbCleanup.SelectedIndex = CurrentJob.FolderSettings.CleanupSchedule;
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Copy)
                View.rdoCopy.Checked = true;
            else if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Move)
                View.rdoMove.Checked = true;
            else if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Delete)
                View.rdoDelete.Checked = true;
            View.numDays.Value = (decimal)CurrentJob.BackupAfterDays;
            View.numHours.Value = CurrentJob.BackupAfterHours;
            View.txtbckLocation.Text = FileOperations.GetRootBackupDestinationFolder(CurrentJob);
            View.OriginalRootBackUpFolder = CurrentJob.RootBackupFolder;
            if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.Daily)
            {
                View.RdoDay.Checked = true;
                View.dtpMntDay.Value = CurrentJob.ServiceTriggerTimeInterval;
            }
            if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.Weekly)
            {
                View.rdoWeek.Checked = true;
                View.cmbWeek.SelectedIndex = CurrentJob.ServiceTriggerDayInterval - 1;
                View.dtpMntDay.Value = CurrentJob.ServiceTriggerTimeInterval;
            }
            if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.Monthly)
            {
                View.rdoMonth.Checked = true;
                View.cmbMonth.SelectedIndex = CurrentJob.ServiceTriggerDayInterval - 1;
                View.dtpMntDay.Value = CurrentJob.ServiceTriggerTimeInterval;
            }
            if (CurrentJob.FolderSettings.FileCheckMode == FileCheckModeEnum.ByModifiedDate)
                View.rdByModified.Checked = true;
            else if (CurrentJob.FolderSettings.FileCheckMode == FileCheckModeEnum.ByCreatedDate)
                View.rdByCreated.Checked = true;
            else
                View.rdByAccessed.Checked = true;
            View.IsUILoading = false;
        }

        public override bool SaveData()
        {
            if (ValidateContents(0) == false)
                return false;
            CurrentJob.CurrentBackupJobMode = BackupJobModeEnum.Folders;
            CurrentJob.JobSetName = View.txtBackupSetName.Text;
            CurrentJob.FolderSettings.IncludeSubfolders = View.chkIncludeSubFolders.Checked;
            CurrentJob.RootSourceFolder = View.txtRootFolder.Text;
            CurrentJob.FolderSettings.CleanupSchedule = View.cmbCleanup.SelectedIndex;
            CurrentJob.FolderSettings.ExcludedLocations.Clear();
            foreach (var item in View.lstExcludedFolders.Items)
            {
                CurrentJob.FolderSettings.ExcludedLocations.Add(item.ToString());
            }
            if (View.rdoCopy.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Copy;
            if (View.rdoMove.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Move;
            if (View.rdoDelete.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Delete;

            CurrentJob.FolderSettings.IncludeEmptyFolders = View.chkDeleteEmptyFolders.Checked;
            CurrentJob.BackupAfterDays = (int)View.numDays.Value;
            CurrentJob.BackupAfterHours = (int)View.numHours.Value;
            CurrentJob.RootBackupFolder = View.OriginalRootBackUpFolder;
            if (View.RdoDay.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.Daily;
                CurrentJob.ServiceTriggerDayInterval = View.cmbWeek.SelectedIndex + 1;
                CurrentJob.ServiceTriggerTimeInterval = View.dtpMntDay.Value;
            }
            else if (View.rdoWeek.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.Weekly;
                CurrentJob.ServiceTriggerDayInterval = View.cmbWeek.SelectedIndex + 1;
                CurrentJob.ServiceTriggerTimeInterval = View.dtpMntDay.Value;
            }
            else if (View.rdoMonth.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.Monthly;
                CurrentJob.ServiceTriggerDayInterval = View.cmbMonth.SelectedIndex + 1;
                CurrentJob.ServiceTriggerTimeInterval = View.dtpMntDay.Value;
            }
            if (View.rdByModified.Checked == true)
                CurrentJob.FolderSettings.FileCheckMode = FileCheckModeEnum.ByModifiedDate;
            else if (View.rdByCreated.Checked == true)
                CurrentJob.FolderSettings.FileCheckMode = FileCheckModeEnum.ByCreatedDate;
            else
                CurrentJob.FolderSettings.FileCheckMode = FileCheckModeEnum.ByAccessedDate;
            return true;
        }

        internal void HndlbtnbckLocationClick()
        {
            string temp = GetBackupLocation(View.txtbckLocation.Text);
            if (temp != "")
            {
                View.txtbckLocation.Text = FileOperations.GetRootBackupDestinationFolder(temp, View.txtRootFolder.Text, View.txtBackupSetName.Text, CurrentJob.JobGUID,BackupJobModeEnum.Folders);
                View.OriginalRootBackUpFolder = temp;
            }
        }

        internal void HndlBackupSetNameLeave()
        {
            if (View.txtBackupSetName.Text != "")
                View.txtbckLocation.Text = FileOperations.GetRootBackupDestinationFolder(View.OriginalRootBackUpFolder, View.txtRootFolder.Text, View.txtBackupSetName.Text, CurrentJob.JobGUID,BackupJobModeEnum.Folders);
            else
                View.txtbckLocation.Text = View.OriginalRootBackUpFolder;
        }

        internal void btnCopyCliptoDestination()
        {
            string temp = GetDirectoryFromClipBoard();
            if (temp != "")
            {
                View.txtbckLocation.Text = temp;
                View.OriginalRootBackUpFolder = View.txtbckLocation.Text;
            }
        }
    }
 
}
